package it.rossignoli.enrico.app.Tesi;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.NfcA;
import android.nfc.tech.NfcB;
import android.nfc.tech.NfcF;
import android.nfc.tech.NfcV;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class RFIDActivity extends Activity {

	private static final int DIALOG_CONFERM_ID = 1;
	private static final int DIALOG_ERROR_ID = 2;
	private static final int DIALOG_INFO_ID = 3;

	private static final int ITEM_MENU_LEAVE = 9;
	private static final int ITEM_MENU_INFO = 8;
	private static final int ITEM_MENU_TRAINING = 10;

	private final static String LOG_TAG = "RFIDActivity";

	private TextView text_rfid;
	private Button button;
	private int mCount = 0;

	private TextView textDialog;
	private TextView textDialogError;
	private ProgressDialog connecting;

	private String name = "";

	private ResponseReceiverRFID receiver;
	private IntentFilter filter;

	private NfcAdapter mAdapter;
	private PendingIntent mPendingIntent;
	private IntentFilter[] mFilters;
	private String[][] mTechLists;
	private String stringTagId;
	public static byte[] tagId;
	public static NfcV nfcv;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.rfid);
		this.text_rfid = (TextView) findViewById(R.id.text_rfid);
		this.button = (Button) findViewById(R.id.button_rfid);

		/*
		 * --------------------------------------------------------------------
		 * impostazioni ricezione risposta dal service
		 */
		filter = new IntentFilter(ResponseReceiverRFID.ACTION_RESP_RFID_CONTROL);
		filter.addAction(ResponseReceiverRFID.ACTION_RESP_RFID_CONNECTTO);
		filter.addAction(ResponseReceiverRFID.ACTION_LEAVEFROMSIB);
		filter.addCategory(Intent.CATEGORY_DEFAULT);
		receiver = new ResponseReceiverRFID();

		if (!SibIntentService.DEMO) {
			/*
			 * ------------------------------------------------------------------
			 * ----------Impostazioni per lettura RFID
			 */
			mAdapter = NfcAdapter.getDefaultAdapter(this);

			// Create a generic PendingIntent that will be deliver to this
			// activity. The NFC stack
			// will fill in the intent with the details of the discovered tag
			// before delivering to
			// this activity.
			mPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

			// Setup an intent filter for all MIME based dispatches
			// IntentFilter ntech = new
			// IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
			IntentFilter ntech = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);

			mFilters = new IntentFilter[] { ntech, };

			// Setup a tech list for all NfcF tags
			mTechLists = new String[][] { new String[] { NfcF.class.getName() }, new String[] { NfcA.class.getName() }, new String[] { NfcB.class.getName() },
					new String[] { NfcV.class.getName() } };
		}
	}

	@Override
	public void onResume() {
		super.onResume();
		registerReceiver(receiver, filter);
		this.button.setText("CLICK TO ENABLE \nAPP RFID READER");
		this.button.setBackgroundColor(android.graphics.Color.WHITE);
		/*
		 * -------------------------------------------------------------------
		 * attivazione ricezione RFID
		 */
		// mAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters,
		// mTechLists);
	}

	@Override
	public void onPause() {
		super.onPause();
		unregisterReceiver(receiver);
		if (!SibIntentService.DEMO)
			mAdapter.disableForegroundDispatch(this);
	}

	public void rfidReader(View button) {
		if (SibIntentService.DEMO) {
			// SystemClock.sleep(1000);
			Intent intent_control = new Intent(RFIDActivity.this, SibIntentService.class);
			intent_control.putExtra(SibIntentService.PARAM_IN_TYPE, SibIntentService.typeIntent.RFID_CONTROL);
			intent_control.putExtra(SibIntentService.PARAM_IN_RFIDID, "01");
			startService(intent_control);
			// showDialog(DIALOG_CONFERM_ID);
		} else {
			/*
			 * ------------------------------------------------------------------
			 * -attivazione ricezione RFID
			 */
			mAdapter.enableForegroundDispatch(this, mPendingIntent, mFilters, mTechLists);
		}
		this.button.setText("APP RFID READER ENABLED");
		this.button.setBackgroundColor(android.graphics.Color.GREEN);
	}

	@Override
	public void onNewIntent(Intent intent) {
		if (!SibIntentService.DEMO) {
			if (SibIntentService.DEBUG)
				Log.i("Foreground dispatch", "Discovered tag with intent: " + intent);
			// this.text_rfid.setText("Discovered tag " + ++mCount);// +
			// " with intent: " + intent);
			String action = intent.getAction();
			if (NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)) {
				Tag tagFromIntent = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
				nfcv = NfcV.get(tagFromIntent);
				tagId = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
				stringTagId = ConvertbyteArrayToHexString(tagId);
				this.text_rfid.setText("RFID ID: " + stringTagId);// +
																	// "\nRFID TAG: "+
																	// nfcv.toString());

				Intent intent_control = new Intent(RFIDActivity.this, SibIntentService.class);
				intent_control.putExtra(SibIntentService.PARAM_IN_TYPE, SibIntentService.typeIntent.RFID_CONTROL);
				intent_control.putExtra(SibIntentService.PARAM_IN_RFIDID, stringTagId);
				startService(intent_control);

				// this.showDialog(DIALOG_CONFERM_ID);
			}
		}
	}

	protected Dialog onCreateDialog(int id) {
		Dialog dialog;
		switch (id) {
		case DIALOG_CONFERM_ID:
			textDialog = new TextView(this);
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("Connect to :");
			builder.setIcon(R.drawable.ic_launcher);
			builder.setCancelable(true);
			if (SibIntentService.DEMO) {
				textDialog.setText("RFID : 01");
			} else {
				textDialog.setText("RFID : " + stringTagId);
			}
			textDialog.setText("");
			builder.setView(textDialog);
			builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {

					/*
					 * a questo punto posso mettere anche qui il caricamento,
					 * per l'attesa dell'esito infatti devo controllare che
					 * l'oggetto al quale mi voglio collegare sia gi inserito
					 * nella sib, altrimenti come posso controllarlo? se non c'
					 * posso dire di passare alla smartificazione dell'oggetto.
					 */
					connecting = ProgressDialog.show(RFIDActivity.this, "Connect", "Connecting....", true, true, new DialogInterface.OnCancelListener() {

						public void onCancel(DialogInterface dialog) {
							toast("Interrupted");

						}

					});

					Intent intent = new Intent(RFIDActivity.this, SibIntentService.class);
					intent.putExtra(SibIntentService.PARAM_IN_TYPE, SibIntentService.typeIntent.RFID_CONNECTTO);
					// -----------------------------------------------------------------------------
					/*
					 * il valore 01 inserito qui come prova va in realt
					 * sostituito con il valore di stringTagId che � il valore
					 * dell'rfid letto dal dispositivo
					 */
					if (SibIntentService.DEMO) {
						intent.putExtra(SibIntentService.PARAM_IN_RFIDID, "01");
					} else {
						intent.putExtra(SibIntentService.PARAM_IN_RFIDID, stringTagId);
					}
					startService(intent);
				}
			});
			builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int id) {
					dialog.dismiss(); // Chiudiamo la finestra di
										// dialogo
				}
			});

			// Vibrator v = (Vibrator)
			// getSystemService(Context.VIBRATOR_SERVICE);
			// v.vibrate(1000);
			dialog = builder.create();
			break;

		case DIALOG_ERROR_ID:
			textDialogError = new TextView(this);
			// Otteniamo il riferimento al Builder
			AlertDialog.Builder builder2 = new AlertDialog.Builder(this);
			// Impostiamo il titolo, il messaggio ed una icona in chaining
			builder2.setTitle(R.string.alertDialogError_label);
			builder2.setIcon(R.drawable.ic_launcher);
			builder2.setCancelable(false);
			textDialogError.setText("");
			builder2.setView(textDialogError);
			// Impostiamo il pulsante di Yes con il relativo listener
			builder2.setPositiveButton(R.string.alertDialogError_positiveLabel, new DialogInterface.OnClickListener() {

				public void onClick(DialogInterface dialog, int id) {
					dialog.dismiss();
				}

			});
			// Ritorniamo l'Alert creato
			Vibrator vi = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
			vi.vibrate(1000);
			dialog = builder2.create();
			break;

		case DIALOG_INFO_ID:
			dialog = createInfoDialog();
			return dialog;
		default:
			dialog = null;
		}
		return dialog;
	}

	private Dialog createInfoDialog() {
		// Otteniamo il riferimento al Builder
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		// Impostiamo il titolo, il messaggio ed una icona in chaining
		builder.setTitle(R.string.alertDialogInfo_label);
		builder.setIcon(R.drawable.ic_launcher);
		builder.setCancelable(false);
		builder.setMessage(R.string.alertDialogInfo_message);
		// Impostiamo il pulsante di Yes con il relativo listener
		builder.setPositiveButton(R.string.alertDialogInfo_positiveLabel, new DialogInterface.OnClickListener() {

			public void onClick(DialogInterface dialog, int id) {
				dialog.dismiss();
			}

		});
		// Ritorniamo l'Alert creato
		return builder.create();
	}

	protected void onPrepareDialog(int id, Dialog dialog) {
		switch (id) {
		case DIALOG_CONFERM_ID:
			textDialog.setText("RFID ID: " + stringTagId);
			textDialog.append("\nDevice name : " + name);
			// Vibrator v = (Vibrator)
			// getSystemService(Context.VIBRATOR_SERVICE);
			// v.vibrate(1000);
			break;
		case DIALOG_ERROR_ID:
			textDialogError.setText("RFID ID : " + stringTagId + " \nNo in sib!");
			Vibrator vi = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
			vi.vibrate(1000);
		case DIALOG_INFO_ID:
			break;
		default:
			break;
		}
	}

	public String ConvertbyteArrayToHexString(byte in[]) {

		byte ch = 0x00;
		int i = in.length - 1;

		if (in != null) {

			String HEXSET[] = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F" };
			// Double length, as you're converting an array of 8 bytes, to 16
			// characters for hexadecimal
			StringBuffer out = new StringBuffer(in.length * 2);

			// You need to iterate from msb to lsb, in the case of using iCode
			// SLI rfid
			while (i >= 0) {
				ch = (byte) (in[i] & 0xF0); // Strip off high nibble
				ch = (byte) (ch >>> 4); // shift the bits down
				ch = (byte) (ch & 0x0F); // must do this is high order bit is
											// on!
				out.append(HEXSET[(int) ch]); // convert the nibble to a String
												// Character
				ch = (byte) (in[i] & 0x0F); // Strip off low nibble
				out.append(HEXSET[(int) ch]); // convert the nibble to a String
												// Character
				i--;
			}
			return (new String(out));
		} else
			return null;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(Menu.FIRST, ITEM_MENU_LEAVE, 1, "Leave");
		menu.add(Menu.FIRST, ITEM_MENU_INFO, 2, "Info");
		menu.add(Menu.FIRST, ITEM_MENU_TRAINING, 3, "Training");

		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {

		case ITEM_MENU_LEAVE:
			myLeave();
			return true;

		case ITEM_MENU_INFO:
			showDialog(DIALOG_INFO_ID);
			return true;

		case ITEM_MENU_TRAINING:
			Intent intent = new Intent(this, ListT.class);
			startActivity(intent);
			return true;

		default:
			return true;
		}
	}

	private void myLeave() {
		Intent i = new Intent(this, SibIntentService.class);
		i.putExtra(SibIntentService.PARAM_IN_TYPE, SibIntentService.typeIntent.LEAVE);
		startService(i);
		connecting = ProgressDialog.show(RFIDActivity.this, "Leave", "Leaving....", true, true, new DialogInterface.OnCancelListener() {

			public void onCancel(DialogInterface dialog) {
				toast("Interrupted");

			}

		});
	}

	@Override
	public void onBackPressed() {
		myLeave();
	}

	private void toast(String text) {
		Toast.makeText(this, text, Toast.LENGTH_LONG).show();
	}

	public class ResponseReceiverRFID extends BroadcastReceiver {

		public static final String ACTION_RESP_RFID_CONTROL = "CONTROL_ID";
		public static final String ACTION_RESP_RFID_CONNECTTO = "CONNECT_TO";
		public static final String ACTION_LEAVEFROMSIB = SibIntentService.ACTION_LEAVEFROMSIB;

		@Override
		public void onReceive(Context context, Intent intent) {
			// Update UI, new "message" processed by SimpleIntentService

			if (intent.getAction().equals(ACTION_RESP_RFID_CONTROL)) {
				if (SibIntentService.DEBUG)
					Log.i(LOG_TAG, " ACTION_RESP_RFID_CONTROL :");
				boolean r = intent.getBooleanExtra(SibIntentService.PARAM_OUT_RESULT, false);
				if (r) {
					if (!intent.getStringExtra("DEVICE_NAME").equals(SibIntentService.PARAM_OUT_NODEVICE)) {
						name = intent.getStringExtra("DEVICE_NAME");
						showDialog(DIALOG_CONFERM_ID);
					} else {
						showDialog(DIALOG_ERROR_ID);
					}
				} else {
					toast("Error in find rfidid device.");
				}
			} else if (intent.getAction().equals(ACTION_RESP_RFID_CONNECTTO)) {
				if (SibIntentService.DEBUG)
					Log.i(LOG_TAG, " ACTION_RESP_RFID_CONNECTTO :");
				boolean r = intent.getBooleanExtra(SibIntentService.PARAM_OUT_RESULT, false);
				if (r) {
					connecting.dismiss();
					// toast("Connessone riuscita!");
					Intent i = new Intent(RFIDActivity.this, MappingActivity.class);
					/*
    			 * 
    			 */
					i.putExtra("SMARTOBJECT_GESTURELIST", intent.getStringArrayListExtra("SMARTOBJECT_GESTURELIST"));
					i.putExtra("DEVICE_EVENTLIST", intent.getStringArrayListExtra("DEVICE_EVENTLIST"));
					i.putExtra("PREVIOUSMAPPING", intent.getStringExtra("PREVIOUSMAPPING"));
					startActivity(i);
					finish();
				} else {
					connecting.dismiss();
					toast("Error in connect to device.");
				}
			} else if (intent.getAction().equals(ACTION_LEAVEFROMSIB)) {
				if (SibIntentService.DEBUG)
					Log.i(LOG_TAG, " ACTION_LEAVEFROMSIB :");
				boolean r = intent.getBooleanExtra(SibIntentService.PARAM_OUT_RESULT, false);
				if (r) {
					connecting.dismiss();
					finish();
				} else {
					connecting.dismiss();
					toast("Error in leave to SIB");
					finish();
				}
			}

		}

	}

}